/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.basic.init;

import java.io.IOException;
import java.util.Properties;

import com.eelpo.cmmp.basic.dao.vo.SystemConfig;
import com.eelpo.cmmp.basic.services.ISystemConfigManageService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * <pre>
 * 系统配置初始化
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */

public class SystemConfigInit implements ApplicationContextAware {

	private static final Logger logger = LoggerFactory.getLogger(SystemConfigInit.class);

	private boolean check;

	public void setCheck(boolean check) {
		this.check = check;
	}

	public boolean isCheck() {
		return check;
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.context.ApplicationContextAware#setApplicationContext
	 * (org.springframework.context.ApplicationContext)
	 */

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		if (isCheck()) {
			try {
				initSystemConfigs((ISystemConfigManageService) context.getBean("systemConfigManageService"));
			} catch (IOException e) {
				logger.error("Init system config fail:{}", e.getMessage());
			}
		}
	}

	public void initSystemConfigs(ISystemConfigManageService systemConfigManageService) throws IOException {

		Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:conf/systemConfig-*.properties");

		for (Resource resource : resources) {
			logger.info("Init system config from file:{}", resource.getFilename());
			Properties prop = new Properties();
			prop.load(resource.getInputStream());
			String[] configs = prop.getProperty("SystemConfig").split(",");
			for (String config : configs) {

				boolean exist = false;

				try {
					exist = systemConfigManageService.checkExist(config.toUpperCase());
				} catch (Exception e) {
					logger.error(e.getMessage());
				}

				if (!exist) {
					SystemConfig systemConfig = new SystemConfig();
					systemConfig.setConfigKey(config.toUpperCase());
					systemConfig.setConfigValue(prop.getProperty(config.concat(".value")));
					systemConfig.setDescription(prop.getProperty(config.concat(".description")));
					systemConfig.setHint(prop.getProperty(config.concat(".hint")));

					try {
						systemConfigManageService.addSystemConfig(systemConfig);
					} catch (Exception e) {
						logger.error("Init system config {} fail:{}", systemConfig, e.getMessage());
					}
				}
			}
		}
	}
}
